package simple.form.db;


import org.apache.log4j.Logger;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * Created by Administrator on 2017/2/27.
 */
public class Session {
    public static Logger log4j = Logger.getLogger(Session.class);

    private static ThreadLocal<Connection> connections = new ThreadLocal();
    private Connection connection;

    private Session(AbsDataSource ds) throws SQLException{
        Connection conn = connections.get();
        if(conn!=null){
            throw new SQLException("已经开始了事物");
        }
        this.connection = ds.getConnection();
        connections.set(connection);
    }

    /**
     * 获取当前的数据库连接
     * @return
     * @throws SQLException
     */
    public static Connection getCurrentConnection()  throws SQLException {
        Connection conn = connections.get();
        if(conn==null){
            throw  new SQLException("当前的数据库Connection不存在");
        }
        return conn;
    }

    /**
     * 创建Session
     * @param ds  数据源
     * @return
     * @throws SQLException
     */
    public static Session create(AbsDataSource ds) throws SQLException{
        return new Session(ds);
    }
    public void beginTransaction() throws SQLException {
        Connection conn = connections.get();

        conn.setAutoCommit(false);

    }

    /**
     * 提交事务
     * @throws SQLException
     */
    public void commit() throws SQLException {
        Connection conn = null;
        try {
            conn = connections.get();
            // 判断事务是否开始了，如果还没有开始事务，则不能提交
            if(conn == null){
                throw new SQLException("还没开始事物");
            }
            conn.commit();
        } catch (SQLException var5) {
            throw var5;
        } finally {
            conn.setAutoCommit(true);
        }

    }

    /**
     * 事务回滚
     * @throws SQLException
     */
    public void rollback() throws SQLException {
        Connection conn = connections.get();
        try {
            conn.rollback();
        } catch (SQLException var9) {
            throw var9;
        } finally {
            try {
                conn.setAutoCommit(true);
            } catch (SQLException var8) {
                throw var8;
            }
        }

    }

    /**
     * 关闭连接
     */
    public void close() {
        Connection conn = connections.get();
        try {
            conn.close();
        } catch (SQLException e) {
            log4j.error("关闭 Connection error",e);
        }
    }

}
